﻿package com.scn.base.web;

import java.io.*;
import java.net.URLEncoder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

import com.scn.base.service.ISysMenuService;
import com.scn.base.service.ISysRolePowerService;
import com.scn.base.service.ISysRoleService;
import com.scn.base.util.DESUtil;
import com.scn.base.util.FuncUtil;
import com.scn.base.util.MD5Util;
import com.scn.base.util.URLCodeUtil;
import com.scn.base.domain.RolePowerVO;
import com.scn.base.domain.RoleVO;
import com.scn.base.domain.UserVO;
import com.scn.base.page.PageVO;
import com.scn.base.page.TreeNode;


/**
 * 
 * 功能描述： 用户角色web
 * @author 作者 gaoxiong@softscn.com
 * @created May 26, 2012 10:47:44 PM
 * @version 1.0.0
 * @date May 26, 2012 10:47:44 PM
 */
@Controller
@SessionAttributes("userinfo")
public class SysRoleController {
	@Autowired
	private ISysRoleService sysRoleService;
	@Autowired
	private ISysRolePowerService sysRolePowerService;
	@Autowired
	private ISysMenuService sysMenuService;
	
	/**
	 * 功能描述：添加角色页面
	 * @return 页面路劲
	 */
	@RequestMapping(value="/roleAdd.html")
	public ModelAndView roleAdd(String SCNMessage){
		ModelAndView mav=new ModelAndView("/sysrole/roleAdd");
		System.out.println(SCNMessage);
		mav.addObject("SCNMessage", SCNMessage);
		return mav;
	}
	
	/**
	 * 功能描述：编辑角色权限页面
	 * @param  roleid   角色编号
	 * @return 页面路劲
	 */
	@RequestMapping(value="/roleFuncSet.html")
	public ModelAndView roleFuncSet(String roleid){
		ModelAndView mav=new ModelAndView("/sysrole/roleFuncSet");
		mav.addObject("roleid", roleid);
		return mav;
	}
	
	/**
	 * 功能描述：添加角色页面
	 * @return 页面路劲
	 */
	@RequestMapping(value="/roleFuncList.html")
	public ModelAndView roleFuncList(){
		ModelAndView mav=new ModelAndView("/sysrole/roleFuncList");
		return mav;
	}
	@RequestMapping(value="/powerSet.html")
	public ModelAndView powerSet(@ModelAttribute("userinfo")UserVO user,String roleid){
    	int srid=Integer.parseInt(roleid);
    	ModelAndView mav=new ModelAndView("/sysrole/rolePowerList");
    	List alist=sysMenuService.selectRolePowerList(srid);
    	TreeNode root = new TreeNode();
		root.setId("1");
		root.setName("根目录");
    	for(Object o:alist){
    		Map map=(Map)o;
    		TreeNode node = new TreeNode();
    		node.setId(map.get("id").toString());
		    node.setName(map.get("name").toString());
		    node.setEname(map.get("ename").toString());
		    node.setLink(map.get("url").toString());
		    node.setImg(map.get("img").toString());
		    node.setFunc(map.get("func").toString());
		    node.setSrpid(map.get("srpid").toString());
		    System.out.println(map.get("pid").toString());
		    node.setParent(root.findChild(map.get("pid").toString()));
		    node.getParent().addChild(node);
    		
    	}
    	mav.addObject("roleid", roleid);
    	mav.addObject("powerRoot",root);
    	//dbLog(user.getUserno(), "SysRoleAction->powerSet", "角色权限展示");
    	return mav;
	}
	@RequestMapping(value="/deleteRole.html")
	public ModelAndView  deleteRole(String sysRoleId){
		sysRolePowerService.deleteRolePowerByRole(Integer.parseInt(sysRoleId));
		sysRoleService.deleteSysRoleById(Integer.parseInt(sysRoleId));
		return new ModelAndView("forward:/roleList.html");
	}
	@RequestMapping(value="/preUpdateSysRole.html")
	public ModelAndView  preUpdateSysRole(String sysRoleId){
		ModelAndView mav=new ModelAndView("/sysrole/rolePreUpdate");
		RoleVO roleVo= sysRoleService.selectRoleById(Integer.parseInt(sysRoleId));
		mav.addObject("roleVo", roleVo);
		return mav;
	}
	@RequestMapping(value="/roleList.html")
	public ModelAndView roleList(@ModelAttribute("userinfo")UserVO user,String currPage ){
		
		ModelAndView mav=new ModelAndView("/sysrole/roleList");
		 if(user==null){
			 mav.addObject("checkmes", "用户名为空！");
			 return mav;
		 }
		int counts=sysRoleService.selectRoleCount();
		 PageVO page=new PageVO();
		 if(currPage==null||"".equals(currPage)){
			 page.setCurPage(1);
		 }else{
			 page.setCurPage(Integer.parseInt(currPage));
		 }
		 page.setRecordCounts(counts);
		 List list=sysRoleService.selectRoleList(page);
		 //dbLog(user.getUserno(), "SysRoleAction->listRole", "角色清单查询");
		 mav.addObject("sysRolelist", list);
		 mav.addObject("pagevo", page);
		return mav;
	}
	
	@RequestMapping(value="/saveRolePower.html")
	public ModelAndView saveRolePower(@ModelAttribute("userinfo")UserVO user,String functionName,String roleid,String currPage,HttpSession session){
		String[] temp1=functionName.split("\\@");
		int t=-1;
		List<RolePowerVO> aList=new ArrayList<RolePowerVO>();
		ModelAndView mav=new ModelAndView("/sysrole/roleList");
		if(user==null){
			mav.addObject("checkmes", "用户名为空！");
			 return mav;
		}
		int srid=Integer.parseInt(roleid);
		
		for(int p=0;p<temp1.length;p++){
			String[] temp2=temp1[p].split("\\#");
			if(temp1[p].trim().equals("")){
				continue;
			}
			if((t=temp2[0].indexOf("FUNC"))>=0){
				String funcid=temp2[0].substring(t+4);
				if(temp2.length==1){
					RolePowerVO rolePower=new RolePowerVO();
					rolePower.setSmid(funcid);
					rolePower.setSrid(srid);
					rolePower.setSrpfunc("");
					aList.add(rolePower);
				}else if(temp2[1].trim().equals("")){
					RolePowerVO rolePower=new RolePowerVO();
					rolePower.setSmid(funcid);
					rolePower.setSrid(srid);
					rolePower.setSrpfunc("");
					aList.add(rolePower);
				}else if(temp2[1].indexOf("FUNC")>=0){
					RolePowerVO rolePower=new RolePowerVO();
					rolePower.setSmid(funcid);
					rolePower.setSrid(srid);
					rolePower.setSrpfunc(temp2[1].replace("FUNC", ""));
					aList.add(rolePower);
				}else{
					RolePowerVO rolePower=new RolePowerVO();
					rolePower.setSmid(funcid);
					rolePower.setSrid(srid);
					rolePower.setSrpfunc("");
					aList.add(rolePower);
				}
			}
		}
		//sysRolePowerService.insertRolePowers(aList,srid);
		sysRolePowerService.deleteAndinsertRolePowers(aList, srid);
		List powerList=sysMenuService.selectRolePower(srid);
		TreeNode root = new TreeNode();
		root.setId("1");
		root.setName("根目录");
		for(Object o:powerList){
			Map map=(Map)o;
	   		TreeNode node = new TreeNode();
	   		node.setId(map.get("id").toString());
			    node.setName(map.get("name").toString());
			    node.setEname(map.get("ename").toString());
			    node.setLink(map.get("url").toString());
			    node.setImg(map.get("img").toString());
			    node.setFunc(map.get("func").toString());
			    node.setSrpid(map.get("srpid").toString());
			    node.setParent(root.findChild(map.get("pid").toString()));
			    node.getParent().addChild(node);
	   	}
		BufferedWriter bw;
		String path=session.getServletContext().getRealPath("/");
		try {
			bw = new BufferedWriter(new FileWriter(path+File.separator+"gxjs"+File.separator+"style1"+File.separator+"Menu"+MD5Util.md5Encrypt(String.valueOf(srid))+".js"));
			bw.write("function writeMenu(menuFlg,basename) {");
			bw.newLine();
			bw.write("var SubImg = basename+'/gximages/style1/menu/menu_arrow_close.gif';");
			bw.newLine();
			bw.write("var SubImgOpen = basename+'/gximages/style1/menu/menu_arrow_open.gif';");
			bw.newLine();
			bw.write("if (menuFlg == false) return;");
			bw.newLine();
			bw.write(FuncUtil.getMenu(root));
			bw.newLine();
			bw.append("}");
			bw.flush();
			bw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		//跳转到角色显示
		int counts=sysRoleService.selectRoleCount();
		 PageVO page=new PageVO();
		 if(currPage==null||"".equals(currPage)){
			 page.setCurPage(1);
		 }else{
			 page.setCurPage(Integer.parseInt(currPage));
		 }
		 page.setRecordCounts(counts);
		 List list=sysRoleService.selectRoleList(page);
		 mav.addObject("sysRolelist", list);
		 mav.addObject("pagevo", page);
		 //dbLog(user.getUserno(),"SysRoleAction->saveRolePower", "角色权限设置");
		 return mav;
	}
	/**
	 * 功能描述：添加角色
	 * @param srname 角色名称
	 * @param srdesc 角色描述
	 * @param srpname 复制角色id
	 * @return 模型视图
	 */
	@RequestMapping(value="/insertSysRoles.html")
	public ModelAndView insertSysRoles(String srname,String srdesc,String srpname){
 	    //往sys_role表中添加记录
		sysRoleService.saveSysRoles(srname,srdesc,srpname);
		return new ModelAndView("redirect:/roleAdd.html?SCNMessage="+DESUtil.encrypt("角色【"+srname+"】添加成功！"));
	}
	
	@RequestMapping(value="/updateSysRoles.html")
	public ModelAndView updateSysRoles(String sysRolesId,String srname,String srdesc,String srpname){	
		RoleVO roleVo= sysRoleService.selectRoleById(Integer.parseInt(sysRolesId));	
		Map<String,String> sysRoleMap=new HashMap<String,String>(4);
		sysRoleMap.put("srname_new",srname);
		sysRoleMap.put("srdesc_new",srdesc);
		sysRoleMap.put("srname_old",roleVo.getName());
		sysRoleMap.put("srdesc_old", roleVo.getDesc());
		sysRoleService.updateSysRole(sysRoleMap);
		Map<String,Object> srpnameMap=new HashMap<String,Object>(2);
		srpnameMap.put("srid_new", Integer.parseInt(srpname));
		srpnameMap.put("srid_old", roleVo.getId());
		sysRolePowerService.updateRolePower(srpnameMap);
		return new ModelAndView("forward:/roleList.html");
	}
	@RequestMapping(value="/initSysRoleList.html")
	public ModelAndView initSysRoleList(@ModelAttribute("userinfo")UserVO userinfo,String sysRoleId,String currPage, HttpSession session){
		
		ModelAndView mav=new ModelAndView("forward:/roleList.html");
		if(userinfo==null){
			mav.addObject("checkmes", "用户名为空！");
			 return mav;
		}
		int srid=Integer.parseInt(sysRoleId);
		List powerList=sysMenuService.selectRolePower(srid);
		TreeNode root = new TreeNode();
		root.setId("1");
		root.setName("根目录");
		for(Object o:powerList){
			Map map=(Map)o;
	   		TreeNode node = new TreeNode();
	   		node.setId(map.get("id").toString());
		    node.setName(map.get("name").toString());
		    node.setEname(map.get("ename").toString());
		    node.setLink(map.get("url").toString());
		    node.setImg(map.get("img").toString());
		    node.setFunc(map.get("func").toString());
		    node.setSrpid(map.get("srpid").toString());
		    node.setParent(root.findChild(map.get("pid").toString()));
		    node.getParent().addChild(node);
	   	}
		 //写入文件
		 writeFile(srid, root,session);
		//跳转到角色显示
		 int counts=sysRoleService.selectRoleCount();
		 PageVO page=new PageVO();
		 if(currPage==null||"".equals(currPage)){
			 page.setCurPage(1);
		 }else{
			 page.setCurPage(Integer.parseInt(currPage));
		 }
		 page.setRecordCounts(counts);
		 List list=sysRoleService.selectRoleList(page);
		 mav.addObject("sysRolelist", list);
		 mav.addObject("pagevo", page);
		// dbLog(user.getUserno(),"SysRoleAction->saveRolePower", "重新生成菜单");
		 return mav;
	}

	//写文件
	private void writeFile(int srid,TreeNode root,HttpSession session){
		BufferedWriter bw;
		String path=session.getServletContext().getRealPath("/");
		try {
			
			bw =new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path+File.separator+"gxjs"+File.separator+"style1"+File.separator+"Menu"+MD5Util.md5Encrypt(String.valueOf(srid))+".js"),"UTF-8"));
			System.out.println(path+"gxjs"+File.separator+"style1"+File.separator+"Menu"+MD5Util.md5Encrypt(String.valueOf(srid))+".js");
			bw.write("function writeMenu(menuFlg,basename) {");
			bw.newLine();
			bw.write("var SubImg = basename+'/gximages/style1/menu/menu_arrow_close.gif';");
			bw.newLine();
			bw.write("var SubImgOpen = basename+'/gximages/style1/menu/menu_arrow_open.gif';");
			bw.newLine();
			bw.write("if (menuFlg == false) return;");
			bw.newLine();
			bw.write(FuncUtil.getMenu(root));
			bw.newLine();
			bw.append("}");
			bw.flush();
			bw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
}
